package com.bkgy.controller.technology.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bkgy.controller.technology.entity.CalProcessDatas;
import com.bkgy.controller.technology.entity.TTechAnnealingParam;
import com.bkgy.controller.technology.mapper.ITechAnnealingParamMapper;
import com.bkgy.controller.technology.service.ITechAnnealingParamService;
import com.bkgy.sys.common.entity.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class TechAnnealingParamServiceImpl extends ServiceImpl<ITechAnnealingParamMapper, TTechAnnealingParam> implements ITechAnnealingParamService {

    @Override
    public void checkParam(Map<String, List<TTechAnnealingParam>> paramMap, CalProcessDatas p) {
        //表面等级代码映射关系，等级编号小于30的都按30看
        Map<String, String> surfaceMap = new HashMap<>();
        surfaceMap.put("1", "30");//21当30
        surfaceMap.put("2", "30");
        surfaceMap.put("3", "30");//31算30
        surfaceMap.put("4", "40");
        surfaceMap.put("5", "50/51");
        surfaceMap.put("6", "50/51");
        surfaceMap.put("9", "30");//9当30
        surfaceMap.put("F", "30");//00当30
        surfaceMap.put("G", "30");//20当30
        surfaceMap.put("S", "30");//10当30

        //TODO 二次焊接判定
//        p.setSecondWeldJudge(0);
//        p.setWeldTimesJudge(0);

        //TODO 不区分品牌，日产、上汽
        //表面等级代码转换
        if (StringUtils.isEmpty(p.getSurfaceAccuClassCode())) {
            p.setSurfaceAccuClassCode("S");
        }
        String suffix = "_" + surfaceMap.get(p.getSurfaceAccuClassCode()) + "_";

        //#1碱浸刷洗槽循环槽碱液电导率平均值
        p.setCalAlkali1WashCondJudge(checkRange(p.getCalAlkali1WashCondAvg(), paramMap.get("2" + suffix)));
        //#2碱浸刷洗槽循环槽碱液电导率平均值
        p.setCalAlkali2WashCondJudge(checkRange(p.getCalAlkali2WashCondAvg(), paramMap.get("2" + suffix)));
        //#1碱浸刷洗槽循环槽碱液温度平均值
        p.setCalAlkali1WashTempJudge(checkRange(p.getCalAlkali1WashTempAvg(), paramMap.get("3" + suffix)));
        //#2碱浸刷洗槽循环槽碱液温度平均值
        p.setCalAlkali2WashTempJudge(checkRange(p.getCalAlkali2WashTempAvg(), paramMap.get("3" + suffix)));
        //电解清洗循环槽碱液电导率平均值
        p.setCalElecCleanCondJudge(checkRange(p.getCalElecCleanCondAvg(), paramMap.get("4" + suffix)));
        //电解清洗循环槽碱液温度平均值
        p.setCalElecCleanTempJudge(checkRange(p.getCalElecCleanTempAvg(), paramMap.get("5" + suffix)));
        //热水漂洗循环槽温度
        p.setCalHotWaterRinseTempJudge(checkRange(p.getCalHotWaterRinseTempAvg(), paramMap.get("7" + suffix)));
        //快冷Z1-2段氢含量
        if (p.getCalRcZ12H2() == null) {
            p.setCalRcZ12H2Judge(-1);
        } else if (p.getCalRcZ12H2().compareTo(BigDecimal.valueOf(28)) <= 0) {
            if (p.getCalHeatH2Avg().compareTo(BigDecimal.valueOf(5.5)) >= 0) {
                p.setCalRcZ12H2Judge(0);
            } else {
                p.setCalRcZ12H2Judge(1);
            }
        } else {
            p.setCalRcZ12H2Judge(0);
        }

        //Htg1氢含量
        p.setCalHeatH2Judge(checkRange(p.getCalHeatH2Avg(), paramMap.get("9" + suffix)));
        //Htg1炉压
        p.setCalHeatFurPressureJudge(checkRange(p.getCalHeatFurPressureAvg(), paramMap.get("10" + suffix)));
        //水淬槽水温
        p.setCalQuenchTempJudge(checkRange(p.getCalQuenchTempAvg(), paramMap.get("11" + suffix)));
        //水淬槽电导率
        p.setCalQuenchCondJudge(checkRange(p.getCalQuenchCondAvg(), paramMap.get("12" + suffix)));
        //平整延伸率实际值均值[%]
        List<TTechAnnealingParam> spmParamList = paramMap.get("14" + suffix);
        if(spmParamList!=null){
            for (TTechAnnealingParam spmParam : spmParamList) {
                String panding = spmParam.getPanding();
                BigDecimal v = BigDecimal.valueOf(Double.parseDouble(panding.substring(2)));
                if(p.getSpmElongAim() == null){
                    p.setCalSpmElongActJudge(-2);
                }else{
                    BigDecimal w1 = p.getSpmElongAim().subtract(v);
                    BigDecimal w2 = p.getSpmElongAim().add(v);
                    if (p.getCalSpmElongActAvg() != null) {
                        if (p.getCalSpmElongActAvg().compareTo(w1) >= 0 && p.getCalSpmElongActAvg().compareTo(w2) <= 0) {
                            p.setCalSpmElongActJudge(0);
                        } else {
                            p.setCalSpmElongActJudge(1);
                        }
                    }
                }
            }
        }else{
            p.setCalSpmElongActJudge(-1);
        }

        List<TTechAnnealingParam> clist = paramMap.get(p.getSteelgrade());
        if (clist != null)
            for (TTechAnnealingParam param : clist) {
                check5Param(param, p);
            }
    }

    //验证单一范围,1不合格，0合格
    public int checkRange(BigDecimal value, List<TTechAnnealingParam> list) {
        if (list == null || list.size() == 0) {
            return -1;
        }
        TTechAnnealingParam param = list.get(0);
        if (value == null) return -1;
        String panding = param.getPanding();
        if (StringUtils.isNotEmpty(panding)) {
            if (panding.startsWith("t")) {
                String c = panding.substring(1, 2);
                BigDecimal v = BigDecimal.valueOf(Double.parseDouble(panding.substring(2)));
                if ("≤".equals(c)) {
                    if (value.compareTo(v) <= 0) return 0;
                    else return 1;
                }
                if ("＜".equals(c)) {
                    if (value.compareTo(v) < 0) return 0;
                    else return 1;
                }
                if ("≥".equals(c)) {
                    if (value.compareTo(v) >= 0) return 0;
                    else return 1;
                }
            } else {
                //范围
                BigDecimal v1 = BigDecimal.valueOf(Double.parseDouble(panding.substring(0, panding.indexOf("t") - 1)));
                BigDecimal v2 = BigDecimal.valueOf(Double.parseDouble(panding.substring(panding.indexOf("t") + 2)));
                //这里范围只有≤
                if (value.compareTo(v1) >= 0 && value.compareTo(v2) <= 0) {
                    return 0;
                } else return 1;
            }
        }
        return -1;//未命中
    }

    /**
     * 验证5项指标
     *
     * @param param
     * @param d
     * @return 命中范围
     */
    private boolean check5Param(TTechAnnealingParam param, CalProcessDatas d) {
        //加热段带温均值
        if (param.getJiare() != null) {
            BigDecimal v1 = param.getJiare().subtract(BigDecimal.TEN);
            BigDecimal v2 = param.getJiare().add(BigDecimal.TEN);
            if (d.getCalHeatStripTempAvg() != null
                    && d.getCalHeatStripTempAvg().compareTo(v1) >= 0
                    && d.getCalHeatStripTempAvg().compareTo(v2) <= 0) {
                d.setCalHeatStripTempJudge(0);
            } else d.setCalHeatStripTempJudge(1);
        }
        //缓冷段带温均值
        if (param.getHuanleng() != null) {
            BigDecimal v1 = param.getHuanleng().subtract(BigDecimal.TEN);
            BigDecimal v2 = param.getHuanleng().add(BigDecimal.TEN);
            if (d.getCalScStripTempAvg() != null
                    && d.getCalScStripTempAvg().compareTo(v1) >= 0
                    && d.getCalScStripTempAvg().compareTo(v2) <= 0) {
                d.setCalScStripTempJudge(0);
            } else d.setCalScStripTempJudge(1);
        }
        //快冷段带温均值
        if (param.getKuaileng() != null) {
            BigDecimal v1 = param.getKuaileng().subtract(BigDecimal.TEN);
            BigDecimal v2 = param.getKuaileng().add(BigDecimal.TEN);
            if (d.getCalRcStripTempAvg() != null
                    && d.getCalRcStripTempAvg().compareTo(v1) >= 0
                    && d.getCalRcStripTempAvg().compareTo(v2) <= 0) {
                d.setCalRcStripTempJudge(0);
            } else d.setCalRcStripTempJudge(1);
        }
        //时效3段带温均值
        if (param.getShixiao() != null) {
            BigDecimal v1 = param.getShixiao().subtract(BigDecimal.valueOf(20));
            BigDecimal v2 = param.getShixiao().add(BigDecimal.valueOf(20));
            if (d.getCalOas3StripTempAvg() != null
                    && d.getCalOas3StripTempAvg().compareTo(v1) >= 0
                    && d.getCalOas3StripTempAvg().compareTo(v2) <= 0) {
                d.setCalOas3StripTempJudge(0);
            } else d.setCalOas3StripTempJudge(1);
        }
        //工艺段速度均值[m/min]
        /*
        if (param.getSudu() != null) {
            String suduExec = param.getSudu();
            if (suduExec.startsWith("v")) {
                String c = suduExec.substring(1, 1);
                BigDecimal v = BigDecimal.valueOf(Double.parseDouble(suduExec.substring(2)));
                if ("≥".equals(c) && d.getCalProcessSpeedAvg().compareTo(v) >= 0) {
                    d.setCalProcessSpeedJudge(0);
                } else
                    d.setCalProcessSpeedJudge(1);
            } else {
                //范围表达式
                BigDecimal v1 = BigDecimal.valueOf(Double.parseDouble(suduExec.substring(0, suduExec.indexOf("v") - 1)));
                BigDecimal v2 = BigDecimal.valueOf(Double.parseDouble(suduExec.substring(suduExec.indexOf("v") + 2)));
                if (d.getCalProcessSpeedAvg().compareTo(v1) >= 0 && d.getCalProcessSpeedAvg().compareTo(v2) <= 0) {
                    d.setCalProcessSpeedJudge(0);
                } else {
                    d.setCalProcessSpeedJudge(1);
                }
            }
        }
        */

        return true;
    }

    @Override
    public ResultData<String> importTechParam() {
        FileInputStream in = null;
        try {
            in = new FileInputStream("D:\\workspace\\项目文档\\生产工艺分析\\连退生产工艺分析\\工艺符合度整理入库.xlsx");
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheetAt(0);
            int lastRowNum = sheet.getLastRowNum();

            for (int i = 1; i <= lastRowNum; i++) {
                XSSFRow row = sheet.getRow(i);
                double col0 = row.getCell(0).getNumericCellValue();
                String col1 = row.getCell(1).getStringCellValue();
                String col2 = row.getCell(2).getStringCellValue().trim();
                String col3 = row.getCell(3).getStringCellValue().trim();
                String col4 = row.getCell(4).getStringCellValue().trim();
                double col5 = row.getCell(5).getNumericCellValue();
                double col6 = row.getCell(6).getNumericCellValue();
                double col7 = row.getCell(7).getNumericCellValue();
                double col8 = row.getCell(8).getNumericCellValue();

                String col11 = row.getCell(9).getStringCellValue().trim();
                TTechAnnealingParam param = new TTechAnnealingParam();
                param.setProNo(col0 + "");
                param.setProName(col1);
                param.setSurface(col2);
                param.setCompany(col3);
                param.setBrand(col4);
                if (col5 > 0) param.setJiare(BigDecimal.valueOf(col5));
                if (col6 > 0) param.setHuanleng(BigDecimal.valueOf(col6));
                if (col7 > 0) param.setKuaileng(BigDecimal.valueOf(col7));
                if (col8 > 0) param.setShixiao(BigDecimal.valueOf(col8));
                param.setPanding(col11);
                save(param);
            }
            excel.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return ResultData.ResultDataSuccess("success");
    }

}
